#encoding=utf-8
'''
Created on 2018-8-9

@author: cooler
'''
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append("./")

from catgateio.GateIO import GateIO
from models import *
from utils.Monitor import Monitor

from key import apiKey,secretKey

import logging.handlers
import logging,time

logger = logging.getLogger()   
logfile = logging.handlers.TimedRotatingFileHandler(os.path.join(os.getcwd(), "logs/market"), 'D', 1, 0)
# 设置后缀名称，跟strftime的格式一样
logfile.suffix = "%Y%m%d.log"
logger.addHandler(logfile) 
#set formater  
#formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") 
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s")  
logfile.setFormatter(formatter)   
logger.setLevel(logging.INFO) 



def get_marketlist():
    gt = GateIO(apiKey,secretKey)
    marketlist = gt.marketlist()
    for v in marketlist['data']:
        m = Market_trade_history()
        m.no = v["no"]    # 1,
        m.symbol = v['symbol']     # 币种标识
        m.name  = v['name']  # 币种名称
        m.name_en = v['name_en']   # 英文名称
        m.name_cn= v['name_cn']   # 中文名称
        m.pair  = v['pair']  # 交易对
        m.rate = float(v['rate'])   # 当前价格
        m.vol_a = float(v['vol_a'])   # 被兑换货币交易量
        m.vol_b = float(str(v['vol_b']).replace(",",""))   # 兑换货币交易量
        m.curr_a = v['curr_a']   # 被兑换货币
        m.curr_b  = v['curr_b']  # 兑换货币
        m.curr_suffix  = v['curr_suffix']  # 货币类型后缀
        m.rate_percent = float(v['rate_percent'])   # 涨跌百分百
        m.trend = v['trend']   # 24小时趋势 up涨 down跌
        m.supply = float(v['supply'])   # 币种供应量
        m.marketcap = int(str(v['marketcap']).replace(",",""))   # 总市值
        m.plot = "0"    # 趋势数据
        m.save()
        

if __name__ == '__main__':
    # get_tickets()
    last_time = time.time()
    while True:
        get_marketlist()
        time.sleep(10)
        now_time = time.time()
        if now_time-last_time>3600:
            Monitor.heart_beat_send("marketList")
            last_time = now_time
            logger.info("get data success!")
        else:
        	logger.info("get data success!")



